﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Pai.LiveStation.Data;
using System.Web.Security;

namespace Pai.LiveStation.Web
{
    public static class CommonHelper
    {
        public static Dictionary<string, int> RankTags(List<Tag> tags)
        {
            Dictionary<string, int> retList = new Dictionary<string, int>();

            foreach (Tag tag in tags)
            {
                if (!retList.ContainsKey(tag.ID.ToLower().Trim()))
                    retList.Add(tag.ID.ToLower().Trim(), 0);
                retList[tag.ID.ToLower().Trim()]++;
            }

            double[] hits = new double[retList.Count];
            int[] vals = retList.Values.ToArray<int>();
            for (int x = 0; x < retList.Count; x++)
                hits[x] = vals[x];

            QuantitativeAnalysis qA = new QuantitativeAnalysis(hits);

            double q1 = qA.Q1();
            double q2 = qA.Q2();
            double q3 = qA.Q3();

            string[] keys = retList.Keys.ToArray<string>();

            for (int x = 0; x < retList.Count; x++)
            {
                String tag = keys[x];

                if (retList[tag] < q1)
                    retList.Remove(tag);
                if (retList[tag] < q2)
                    retList[tag] = 3;
                if (retList[tag] < q3)
                    retList[tag] = 2;
                if (retList[tag] >= q3)
                    retList[tag] = 1;
            }

            return retList;
        }

        public static Author GetOrCreateAuthorForUser(MembershipUser user)
        {
            Models.aspnet_User temp = new Models.aspnet_User();
            temp.UserId = (Guid)user.ProviderUserKey;
            temp.UserName = "temp";
            return GetOrCreateAuthorForUser(temp);
        }


        public static Author GetOrCreateAuthorForUser(Models.aspnet_User user)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                MemberProfile profile = dc.MemberProfiles.Where(x=>x.UserID.Equals((Guid)user.UserId)).FirstOrDefault();

                if(profile == null)
                    return null;

                Author author = dc.Authors.Where(x => x.Name.Equals(profile.Name)).FirstOrDefault();

                if (author == null)
                {
                    author = new Author();
                    author.Name = profile.Name;
                    dc.Authors.InsertOnSubmit(author);
                    dc.SubmitChanges();
                }
                return author;
            }
        }
    }
}